#include "DI8Input.h"

namespace Input_DI {
	HRESULT DIKBInputDevice::Init(HINSTANCE hInstance, HWND hwnd) {
		if(!g_Initialized) {
			HRESULT hr = 
			DirectInput8Create(	hInstance,
								DIRECTINPUT_VERSION,
								IID_IDirectInput8,
								(void**)&g_DI,
								NULL);
			g_Initialized = true;
		};

		HRESULT hr = g_DI->CreateDevice(GUID_SysKeyboard,
							  &DIDev,
							  NULL);
		hr = DIDev->SetDataFormat(&c_dfDIKeyboard);
		hr = DIDev->SetCooperativeLevel(hwnd,
										DISCL_BACKGROUND | DISCL_NONEXCLUSIVE);
		
		hr = DIDev->Acquire();

		return hr;
	}

	void DIKBInputDevice::Release(void) {
		if(DIDev != NULL) {
			DIDev->Release();
			DIDev = NULL;
		};
	}

	void DIKBInputDevice::Update(void) {
		memcpy(BufferLast, BufferNow, sizeof(char) * 256);
		DIDev->GetDeviceState(sizeof(BufferNow),
							  (LPVOID)&BufferNow);
	}

	bool DIKBInputDevice::KeyDown(int Key) {
		char Val = BufferNow[Key];
		if(Val == -128)
			return true;
		return false;
	}

	bool DIKBInputDevice::KeyUp(int Key) {
		char Val = BufferNow[Key];
		if(Val != -128)
			return true;
		return false;
	}

	bool DIKBInputDevice::KeyPress(int Key) {
		char Val1 = BufferNow[Key];
		char Val2 = BufferLast[Key];
		if(Val1 < Val2)
			return true;
		return false;
	}

	bool DIKBInputDevice::KeyRelease(int Key) {
		char Val1 = BufferNow[Key];
		char Val2 = BufferLast[Key];
		if(Val1 > Val2)
			return true;
		return false;
	}
}